<template>
  <div id="app">
    <el-container>
      <el-main id="pageMain">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="网点/机构名称:">
            <el-input v-model="search.searchObj.siteName" @keydown.13.native="queryListMethod"
                      placeholder="请输入网点/机构名称"
                      :value="null" clearable></el-input>
          </el-form-item>

          <el-form-item label="目的网点:" prop="destinationCity">
            <el-cascader v-model="addrSelect" placeholder="可搜索" :options="options" filterable clearable
                         @change="handleChange">
              <template slot-scope="{ node, data }">
                <span>{{ data.label }}</span>
              </template>
            </el-cascader>
          </el-form-item>

          <el-form-item label="任务分配状态:" prop="destinationCity">
            <el-select v-model="search.searchObj.jobStatus" placeholder="请选择分配状态">
              <el-option label="全部" value="0"></el-option>
              <el-option label="已分配" value="1"></el-option>
              <el-option label="未分配" value="2"></el-option>
            </el-select>
          </el-form-item>


          <el-form-item>
            <el-button type="primary" @click="queryListMethod">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="cleanSearch">清空</el-button>
          </el-form-item>
          <el-form-item>
<!--            <el-button type="success" icon="el-icon-" >刷新</el-button>-->
            <el-button  type="success" icon="el-icon-refresh" @click="this.flushPage"></el-button>
          </el-form-item>
        </el-form>
        <el-table :data="dataList" align="center" border style="width: 100%" height="390px">
          <el-table-column align="center" label="编号" type="index" width="85px">
          </el-table-column>
          <el-table-column align="center" label="机构名称" prop="name"></el-table-column>
          <el-table-column align="center" label="机构简称" prop="abbreviation"></el-table-column>
          <el-table-column align="center" label="所在区" prop="address"></el-table-column>
          <el-table-column align="center" label="联系电话" prop="contractNumber"></el-table-column>
          <el-table-column align="center" label="营业时间" prop="businessHours"></el-table-column>
          <el-table-column align="center" label="每日调度时间" prop="scheduleConf">
            <template slot-scope="scope">{{ scope.row.scheduleConf | convertCronToReadable }}</template>
          </el-table-column>
          <el-table-column align="center" label="调度策略" prop="executorParam">
            <template v-slot="data">
              <span v-for="(item) in executorParamOption" :key="item.value" v-if="item.value == data.row.executorParam">{{
                  item.name
                }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="运行状态" prop="triggerStatus">
            <template v-slot="data">
              <span v-if="data.row.triggerStatus == null || data.row.triggerStatus == ''" style="color: red">
                未设置任务
              </span>
              <span v-if="data.row.triggerStatus == 0">
                <el-switch readonly :value="false" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
              </span>

              <span v-if="data.row.triggerStatus == 1">
                <el-switch readonly :value="true" active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
              </span>
            </template>
          </el-table-column>
          <!--          <el-table-column align="center" label="调度备注" prop="jobDesc"></el-table-column>-->
          <el-table-column align="center" label="设置自动调度时间" prop="id">
            <template v-slot="data">
              <span v-if="data.row.executorHandler == null || data.row.executorHandler == ''">
                <el-button @click="addMethod(data.row)" type="success" icon="el-icon-check"></el-button>
              </span>
              <span v-else>
                <el-button type="primary" @click="centerDialogVisible = true" @click.native="editCurrentObj(data.row)"
                           icon="el-icon-edit"></el-button>
              </span>

            </template>
          </el-table-column>
        </el-table>
        <div style="height: 30px"></div>
        <el-footer>
          <div class="block">
            <el-pagination :current-page="search.currentPage" :page-size="search.pageSize" :page-sizes="[5, 10, 15, 20]"
                           :total="search.total" layout="total, sizes, prev, pager, next, jumper"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange">
            </el-pagination>
          </div>
        </el-footer>
      </el-main>
    </el-container>


    <el-form :model="currentObjTemp" ref="currentObjTemp" v-if="centerDialogVisible" label-width="100px"
             class="demo-ruleForm">
      <el-dialog :visible.sync="centerDialogVisible" center title="操作调度" top="20px" width="50%">
        <span>
          <el-tabs type="border-card">
            <el-tab-pane>
              <span slot="label"><i class="el-icon-date"></i> 操作调度</span>
              <el-form-item label="机构名称" prop="name">
                <el-input readonly v-model="currentObjTemp.name" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item label="派发时间" prop="scheduleConf" :rules="[
                { required: true, message: '每日订单自动派发时间不能为空' },
              ]">
                <el-time-select v-model="currentObjTemp.scheduleConf" :picker-options="{
                  start: '01:00',
                  step: '01:00',
                  end: '24:00'
                }" placeholder="选择时间">
                </el-time-select>
              </el-form-item>
              <el-form-item label="调度策略" prop="executorParam" :rules="[
                { required: true, message: '调度策略不能为空' },
              ]">
                <el-select v-model="currentObjTemp.executorParam" placeholder="请选择调度策略">
                  <!--                  <el-option label="距离最少" value="distanceLeast"></el-option>-->
                  <!--                  <el-option label="成本最少" value="costLeast"></el-option>-->
                  <!--                  <el-option label="中转最少" value="conversionLeast"></el-option>-->
                  <!--                  <el-option label="时间最少" value="timeLeast"></el-option>-->
                  <el-option :label="data.name" :value="data.value" v-for="(data) in executorParamOption"
                             :key="data.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="运行状态" v-if="addOrUpdate == 'updateOrStartJob'">
                <el-switch v-model="currentObjTemp.triggerStatus" inactive-value="0" active-value="1"
                           active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
              </el-form-item>
              <el-form-item label="调度备注" prop="jobDesc" :rules="[
                { required: true, message: '调度备注不能为空' },
              ]">
                <el-input :autosize="{ minRows: 4, maxRows: 5 }" maxlength="50" type="textarea"
                          v-model="currentObjTemp.jobDesc" autocomplete="off"></el-input>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitTheCurrentObjTemp('currentObjTemp')">提 交</el-button>
        </span>
      </el-dialog>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import {
  provinceAndCityData,
  regionData,
  provinceAndCityDataPlus,
  regionDataPlus,
  CodeToText,
  TextToCode
} from 'element-china-area-data'
import CronParser from "cron-parser";

export default {
  filters: {
    convertCronToReadable(cronExpression) {
      if (!cronExpression) {
        return ''
      }
      const CronParser = require('cron-parser');
      try {
        const interval = CronParser.parseExpression(cronExpression).next();
        const nextExecutionTime = interval.toDate().toLocaleString();
        return nextExecutionTime.substring(nextExecutionTime.indexOf(' '), nextExecutionTime.length - 3);
        // return nextExecutionTime;
      } catch (error) {
        console.error('无法解析cron表达式:', error);
        return null;
      }
    },
  },
  name: "regionDataPlus",
  data() {
    return {
      options: regionData,
      addrSelect: [],
      executorParamOption:
        [
          {'name': '距离最少', 'value': 'distance'},
          {'name': '成本最少', 'value': 'cost'},
          {'name': '中转最少', 'value': 'transfer'},
          {'name': '时间最少', 'value': 'estimatedTime'},
        ],
      search: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
        searchObj: {
          siteName: "",
          districtId: "",
          jobStatus: '0',
        },
      },
      centerDialogVisible: false,
      dataList: [],
      currentObjTemp: {},
      addOrUpdate: 'updateOrStartJob',
    }
  },
  watch: {
    'search.currentPage': function () {
      this.queryListMethod()
    },
    'search.pageSize': function () {
      this.queryListMethod()
    },
  },
  methods: {
    async flushPage(){
      await axios.post("/api/dispatch-service/SmartDispatch/flushPage")
      await this.queryListMethod()
    },
    convertCronToReadable(cronExpression) {
      if (!cronExpression) {
        return ''
      }
      const CronParser = require('cron-parser');
      try {
        const interval = CronParser.parseExpression(cronExpression).next();
        const nextExecutionTime = interval.toDate().toLocaleString();
        return nextExecutionTime.substring(nextExecutionTime.indexOf(' '), nextExecutionTime.length - 3);
        // return nextExecutionTime;
      } catch (error) {
        console.error('无法解析cron表达式:', error);
        return null;
      }
    },

    handleChange(value) {
      this.search.searchObj.districtId = value[2];
    },
    cleanSearch() {
      this.addrSelect = [],
        Object.keys(this.search.searchObj).forEach(key => (this.search.searchObj[key] = ''));
    },
    editCurrentObj(row) {
      this.currentObjTemp = JSON.parse(JSON.stringify(row))
      this.currentObjTemp.id=this.currentObjTemp.jobId
      this.centerDialogVisible = true
      this.addOrUpdate = 'updateOrStartJob'
      this.currentObjTemp.scheduleConf = this.convertCronToReadable(row.scheduleConf)
    },
    addMethod(row) {
      Object.keys(this.currentObjTemp).forEach(key => (this.currentObjTemp[key] = ''));
      this.currentObjTemp.author = row.id
      this.currentObjTemp.name = row.name
      this.currentObjTemp.triggerStatus = 0
      this.centerDialogVisible = true
      this.addOrUpdate = 'addSmartDispatch'
    },

    // cleanCurrentObj() {
    //   // this.$refs['currentObjTemp1'].resetField()
    //   // this.$refs['currentObjTemp1'].clearValidate()
    //   // Object.keys(this.currentObjTemp).forEach(key => (this.currentObjTemp[key] = ''));
    // },
    handleSizeChange(val) {
      this.search.pageSize = val
    },
    handleCurrentChange(val) {
      this.search.currentPage = val
    },

    async queryListMethod() {
      let newVar = await axios.post('/api/dispatch-service/pd-order-classify/queryCoreOrgList', this.search);
      console.log(newVar.data.list)
      this.dataList = newVar.data.list
      this.search.total = newVar.data.total
      if(this.search.total){
        this.$message({
          type: 'success',
          message: '查询成功！',
          center: true,
        });
      }
    },

    submitTheCurrentObjTemp(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await this.addSmartJob()
        } else {
          this.$message({
            type: 'warning',
            message: '还有未填充完的选项！',
            center: true,
          });
          return false;
        }
      });
    },
    async addSmartJob() {
      console.log(this.currentObjTemp)
      let newVar = await axios.post('/api/dispatch-service/SmartDispatch/' + this.addOrUpdate, this.currentObjTemp)
      if (newVar.data.code == 200) {
        this.$message({
          type: 'success',
          message: '操作成功！',
          center: true,
        });
        this.centerDialogVisible = false
        await this.queryListMethod()

      } else {
        this.$message({
          type: 'error',
          message: newVar.data.message,
          center: true,
        });
      }
    },
  },
  created() {
    this.queryListMethod()
  }
}
</script>

<style scoped>
#pageMain {
  height: 570px;
}

.el-footer {
  text-align: center;
}

* {
  letter-spacing: 3px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
